package csm.web.core;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csm.common.StringUtil;
import csm.web.core.sitemap.PathInfo;
import csm.web.core.sitemap.SiteMap;

/**
 * 사용자의 모든 요청을 캡쳐합니다.
 */
public class ServiceControllerServlet extends HttpServlet {

	/**	 */
	private static final long serialVersionUID = -6906818005338349060L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public ServiceControllerServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response, "GET");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response, "POST");
	}

	protected Object populate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			// 요청uri에 따라 Velocity 처리 용 서블릿을 생성하여 반환한다.
			PathInfo pathInfo = SiteMap.getInstance().getPathInfo(
					getServletContext(), request);

			if( pathInfo == null )
				throw new Exception("Invalid request URI!, your request uri pattern was not defined in SITEMAP information.");

			if (pathInfo.isRedirectAction()) {
				if (StringUtil.isNullOrEmpty(pathInfo.getTarget()))
					throw new Exception("Redirect action required but RedirectPath was not founded in SITEMAP information.");

				// TODO redirect 할 경우, 목적지에 추가적으로 파마메터를 붙여서 보내야 하는 부분을 고려해야 한다.
				response.sendRedirect(pathInfo.getTarget());
				return null;
			}

			if (pathInfo.isForwardAction()) {
				if (StringUtil.isNullOrEmpty(pathInfo.getTarget()))
					throw new Exception("Forward action required but ForwardPath was not founded in SITEMAP information.");

				RequestDispatcher disp = getServletContext()
						.getRequestDispatcher(pathInfo.getTarget());
				disp.forward(request, response);
				return null;
			}

			return pathInfo.getInstance(getServletConfig());
		} catch (Exception e) {
			return new ErrorServlet();
		}
	}

	private void doService(HttpServletRequest request, HttpServletResponse response, String method) throws ServletException ,IOException {
		try
		{
			Object obj = populate(request, response);

			if (obj instanceof VelocityServletBase)
			{
				VelocityServletBase viewServlet = (VelocityServletBase)obj;
				viewServlet.service(request, response);
			}
			else if (obj instanceof HttpServlet)
			{
				HttpServlet servlet = (HttpServlet)obj;
				servlet.service(request, response);
			}

		} catch (Exception e) {
			// TODO 에러 페이지로 포워드 하는 루틴
			e.printStackTrace();
		}
	}
}
